import request from '@/util/request'
import base64 from '@/util/base64'
import wx from 'weixin-js-sdk'

// get config
const getConfig = (data) => {
  return request({
    url: '/apis/wx/share/index',
    method: 'post',
    data
  })
}

const url = window.location.href

/* eslint-disable */
export const share = (params) => {
  return new Promise((resolve, reject) => {
    // api request
    getConfig({ url }).then(response => {
      let { data } = response
      data = base64.parse(data)

      // 分享调试
      // console.log(data)

      // wx config
      wx.config({
        debug: false,
        appId: data.appId,
        timestamp: data.timestamp,
        nonceStr: data.nonceStr,
        signature: data.signature,
        jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData']
      })

      // wx
      wx.ready(() => {

        // “分享给朋友”及“分享到QQ”按钮的分享内容
        wx.updateAppMessageShareData({
          title: params.title,
          link: params.link,
          imgUrl: params.image,
          desc: params.desc,
          success: res => {
            // 分享成功，返回res信息
            resolve(res)
          }
        })
        // “分享到朋友圈”及“分享到QQ空间”按钮的分享内容
        wx.updateTimelineShareData({
          title: params.title,
          link: params.link,
          imgUrl: params.image,
          // desc: params.desc,
          success: res => {
            // 分享成功，返回res信息
            resolve(res)
          }
        })
      })

      // wx.fail(() => {
      //   reject()
      // })
      // wx.cancel(() => {
      //   reject()
      // })

    })
  })
}
